<template>
	<div class="app-container">
		<!--表单组件-->
		<el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0"
			:title="crud.status.title" width="580px">
			<el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
				<el-form-item label="教师">
					<el-tag>{{ form.teacherName }}</el-tag>
				</el-form-item>
				<el-row :gutter="0.5">
					<el-col :span="8">
						<el-form-item label="班级">
							<el-select v-model="form.classId" clearable filterable placeholder="请选择"
								style="width: 100px;" @change="setNameWithClass">
								<el-option v-for="item in classes" :key="item.classId" :label="item.name"
									:value="item.classId" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="16">
						<el-form-item label="课程">
							<el-select v-model="form.courseId" clearable filterable placeholder="请选择"
								style="width: 280px;" @change="setNameWithCourse">
								<el-option v-for="item in courses" :key="item.courseId" :label="item.name"
									:value="item.courseId" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="考勤名称">
					<el-input v-model="form.name" style="width: 460px;" />
				</el-form-item>

				<el-row :gutter="0.5">
					<el-col :span="12">
						<el-form-item label="时间">
							<el-date-picker v-model="form.date" type="datetime" format="yyyy-MM-dd HH:mm:ss"
								value-format="yyyy-MM-dd HH:mm:ss" style="width: 200px;" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="状态">
							<el-radio v-model="form.enabled" v-for="item in dict.data_status" :key="item.id"
								:label="item.value">{{ item.label }}</el-radio>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="text" @click="crud.cancelCU">取消</el-button>
				<el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
			</div>
		</el-dialog>
		<!-- 考勤列表 -->
		<el-row :gutter="10">
			<el-card class="box-card">
				<!--工具栏-->
				<div class="head-container">
					<el-select v-model="query.periodId" clearable filterable placeholder="培训期次" class="filter-item"
						style="width: 300px;" @change="selPeriodChange">
						<el-option v-for="item in periods" :key="item.periodId" :label="item.name"
							:value="item.periodId" />
					</el-select>
					<el-select v-model="query.classId" clearable filterable placeholder="班级" class="filter-item"
						style="width: 100px;">
						<el-option v-for="item in classes" :key="item.classId" :label="item.name"
							:value="item.classId" />
					</el-select>
					<el-select v-model="query.courseId" clearable filterable placeholder="课程" class="filter-item"
						style="width: 260px;">
						<el-option v-for="item in courses" :key="item.courseId" :label="item.name"
							:value="item.courseId" />
					</el-select>
					<rrOperation />
					<!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
					<crudOperation :permission="permission" />

					<!--表格渲染-->
					<el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
						@selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
						<el-table-column type="selection" width="50" />
						<el-table-column prop="name" label="名称" />
						<el-table-column prop="classModel.period.name" label="培训期次" width="230">
							<template slot-scope="scope">
								{{ scope.row.classModel.period.name }}
							</template>
						</el-table-column>
						<el-table-column prop="teacher.name" label="教师" width="80" />
						<el-table-column prop="classModel.name" label="班级" width="80" />
						<el-table-column prop="course.name" label="课程" width="180" />
						<el-table-column prop="date" label="时间" width="135" />
						<el-table-column label="状态" align="center" prop="enabled" width="70">
							<template slot-scope="scope">
								<el-switch v-model="scope.row.enabled" active-color="#409EFF" inactive-color="#F56C6C"
									@change="changeEnabled(scope.row, scope.row.enabled,)" />
							</template>
						</el-table-column>
						<el-table-column v-if="checkPer(['admin','attendance:edit','attendance:del'])" label="操作"
							width="115px" align="center">
							<template slot-scope="scope">
								<udOperation :data="scope.row" :permission="permission" />
							</template>
						</el-table-column>
					</el-table>
					<!--分页组件-->
					<pagination />
				</div>
			</el-card>
		</el-row>

		<el-row :gutter="10" style="margin-top: 5px;">
			<el-card class="box-card" shadow="hover">
				<div slot="header" class="clearfix">
					<span>考勤详情<label v-if="attendanceName != ''">——{{ attendanceName }}</label></span>
					<!-- 					<el-button
						v-if="checkPer(['admin','attendance:add']) && this.$refs.attendanceDetail && this.$refs.attendanceDetail.query.attendanceName"
						class="filter-item" size="mini" style="float: right;padding: 4px 10px" type="primary"
						icon="el-icon-plus" @click="$refs.attendanceDetail && $refs.attendanceDetail.crud.toAdd()">新增
					</el-button> -->
				</div>
				<attendanceDetail ref="attendanceDetail" :permission="permission" />
			</el-card>
		</el-row>
	</div>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import attendanceDetail from './attendanceDetail'
	import crudAttendance from '@/api/attendance'
	import CRUD, {
		presenter,
		header,
		form,
		crud
	} from '@crud/crud'
	import rrOperation from '@crud/RR.operation'
	import crudOperation from '@crud/CRUD.operation'
	import udOperation from '@crud/UD.operation'
	import pagination from '@crud/Pagination'
	import {
		getClasses
	} from '@/api/class'
	import {
		getCourses
	} from '@/api/course'
	import {
		getTeacher
	} from '@/api/teacher'
	import {
		getPeriods
	} from '@/api/period'

	const defaultForm = {
		attendanceId: null,
		name: null,
		teacherId: null,
		teacherName: null,
		date: new Date(),
		classId: null,
		enabled: 'true',
		attendanceDetails: []
	}
	export default {
		name: 'Attendance',
		components: {
			pagination,
			crudOperation,
			rrOperation,
			udOperation,
			attendanceDetail
		},
		mixins: [presenter(), header(), form(defaultForm), crud()],
		dicts: ['data_status'],
		cruds() {
			return CRUD({
				title: '考勤',
				url: 'api/attendance',
				idField: 'attendanceId',
				sort: 'attendanceId,desc',
				crudMethod: {
					...crudAttendance
				}
			})
		},
		data() {
			return {
				periods: [],
				classes: [],
				courses: [],
				teacher: null,
				attendanceName: '',
				permission: {
					add: ['admin', 'attendance:add'],
					edit: ['admin', 'attendance:edit'],
					del: ['admin', 'attendance:del']
				},
				rules: {}
			}
		},
		computed: {
			...mapGetters([
				'user'
			])
		},
		methods: {
			// 钩子：在获取表格数据之前执行，false 则代表不获取数据
			[CRUD.HOOK.beforeRefresh]() {
				if (this.$refs.attendanceDetail) {
					this.$refs.attendanceDetail.query.attendanceName = ''
				}

				// 加载培训期次信息
				this.periods = [] // 先清空之前的培训期次信息
				getPeriods({
					enabled: true
				}).then(res => {
					this.periods = res.content
				})
				// this.classes = []
				// getClasses({
				// 	enabled: true
				// }).then(res => {
				// 	this.classes = res.content
				// })
				this.courses = []
				getCourses({
					enabled: true
				}).then(res => {
					this.courses = res.content
				})

				var params = null
				for (var i = 0; i < this.user.roles.length; i++) {
					if (this.user.roles[i].name == '超级管理员' || this.user.roles[i].name == '招就处管理员')
						params = {
							enabled: 'true'
						}
					else if (this.user.roles[i].name == '教师用户')
						params = {
							enabled: 'true',
							teacherId: this.user.id
						}
				}
				this.crud.params = params

				return true
			},
			[CRUD.HOOK.afterToCU](crud, form) {
				getTeacher({
					userId: this.user.id
				}).then(res => {
					if (res.content.length >= 1) {
						this.teacher = res.content[0]
						form.teacherId = this.teacher.teacherId
						form.teacherName = this.teacher.name
					}
				})

				form.enabled = `${form.enabled}`
			},
			selPeriodChange(e){
				//加载班级信息
				getClasses({
					periodId: e,
					enabled: true
				}).then(res => {
					this.classes = res.content
					
				})
			},
			setName() {
				var className = ''
				var courseName = ''
				var count = 0

				if (this.form.classId) {
					for (var i = 0; i < this.classes.length; i++) {
						if (this.classes[i].classId == this.form.classId)
							className = this.classes[i].name
					}
				}
				if (this.form.courseId) {
					for (var i = 0; i < this.courses.length; i++) {
						if (this.courses[i].courseId == this.form.courseId)
							courseName = this.courses[i].name
					}
				}

				this.form.name = this.form.teacherName + '_' + className + '_' + courseName

				if (this.form.classId && this.form.courseId) {
					setTimeout(() => {
						crudAttendance.count(this.user.id, this.form.classId, this.form.courseId).then(res => {
							count = res //获取当前教师选定班级选定课程的考勤次数

							count = count + 1
							this.form.name = this.form.name + '_第' + count + '次考勤'
						})
					}, 100)
				}
			},
			setNameWithClass(e) {
				this.form.classId = e
				this.setName()
			},
			setNameWithCourse(e) {
				this.form.courseId = e
				this.setName()
			},
			// 改变状态
			changeEnabled(data, val) {
				this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					crudAttendance.edit(data).then(res => {
						this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE
							.SUCCESS)
					}).catch(err => {
						data.enabled = !data.enabled
						console.log(err.response.data.message)
					})
				}).catch(() => {
					data.enabled = !data.enabled
				})
			},
			// 选中考勤后，设置考勤详情数据
			handleCurrentChange(val) {
				if (val) {
					this.$refs.attendanceDetail.attendanceName = val.name
					this.attendanceName = val.name
					this.$refs.attendanceDetail.attendanceId = val.attendanceId
					this.$refs.attendanceDetail.query.attendanceId = val.attendanceId
					this.$refs.attendanceDetail.crud.toQuery()
				}
			},
			// 编辑前将考勤明细临时清空，避免日志入库数据过长
			[CRUD.HOOK.beforeToEdit](crud, form) {
				// 将角色的菜单清空，避免日志入库数据过长
				form.attendanceDetails = null
			}

		}
	}
</script>

<style scoped>

</style>
